# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Time    : 2021/12/9 10:30
# @Author  : zuodengbo
# @Email   : zuodb@amoydx.com
# @File    : send_email
# @Software: PyCharm
import re
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from sanic.log import logger

from config import EmailConfig
from utils.const import RespCode


class Email(object):
    def __init__(self):
        em = EmailConfig()
        self.server = em.server
        self.user = em.user
        self.password = em.password
        self.port = em.port
        self.sender = em.sender
        self.title = em.subject
        self.receiver = []

        self.msg = MIMEMultipart("mixed")

    def email_header(self, to: list):
        """
        邮件头
        :return:
        """
        self.msg["From"] = self.sender
        self.msg["To"] = ";".join(to)
        self.msg["Subject"] = self.title

    def email_login(self):
        """
        邮件服务器登录
        :return:
        """
        try:
            smtp_server = smtplib.SMTP_SSL(self.server, self.port)
        except Exception as e:
            msg = "When connect email server, exception occurred: {}".format(e)
            logger.error(msg)

            return RespCode.CONNECT_EMAIL_SERVER_FAILED, msg

        else:
            try:
                # login
                smtp_server.login(self.user, self.password)
            except smtplib.SMTPAuthenticationError as e:
                msg = "Email server login failed:{}".format(e)
                logger.error(msg)
                return RespCode.EMAIL_SERVER_LOGIN_FAILED, msg

            return RespCode.SUCCESS, smtp_server

    def send_handle(self, to: list, file_path=None, content=None):
        """
        邮件发送处理
        :param to:
        :param file_path:
        :param content:
        :return:
        """
        if content:
            self.msg = MIMEText(content, "plain", "utf-8")
        elif file_path:
            with open("%s" % file_path, "rb") as fn:
                f = fn.read()
                attach = MIMEText(f, "base64", "utf-8")
                attach["Content-Type"] = "application/octet-stream"

                file_name = re.split(r"[\\|/]", file_path)

                attach["Content-Disposition"] = "attachment; filename='%s'" % file_name[-1]

                self.msg.attach(attach)
        else:
            self.msg = MIMEText("Borden System", "plain", "utf-8")

        self.email_header(to)

        code, smtp_server_or_msg = self.email_login()
        if code != RespCode.SUCCESS:
            return code, smtp_server_or_msg
        # send email
        smtp_server_or_msg.sendmail(self.sender, to, self.msg.as_string())
        msg = "Send '{}' Success ! Receiver: {}".format(self.title, to)
        logger.info(msg)
        smtp_server_or_msg.quit()

        return RespCode.SUCCESS, msg


mail = Email()

if __name__ == '__main__':

    t = ["zuodb@amoydx.com", ]
    c = "验证码：123456"
    mail.send_handle(t, content=c)
